package qiyu.im.core.server.constants;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 解码器就是把ImMsg读取出来,并对ImMsg进行校验,如果IMMsg合法那么就把它加到out里面
 * 以便后续处理器能够读取到.
 * User: sfx
 * Date: 2023-10-16
 * Time: 18:12
 */
public class ImDecoder extends ByteToMessageDecoder {

    private static final int BASIC_LENGTH = 2 + 4 + 4;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        // 读取整个消息看长度是否合法
        if (byteBuf.readableBytes() >= BASIC_LENGTH) {
            // 长度格式合法
            //1. 校验魔数
            short magic = byteBuf.readShort();
            if (magic != IMConstants.DEFAULT_MAGIC) {
                ctx.close();
                System.out.println("magic不合法,消息受损");
                return;
            }
            //2. 读取业务code
            int code = byteBuf.readInt();
            // 3. 校验消息长度
            int len = byteBuf.readInt();
            // 4. 读取消息体
            if (byteBuf.readableBytes() < len) {
                ctx.close();
                System.out.println("消息不合法,消息受损");
                return;
            }

            byte[] bytes = new byte[len];
            byteBuf.readBytes(bytes);
            ImMsg msg = new ImMsg();
            msg.setMagic(magic);
            msg.setBody(bytes);
            msg.setCode(code);
            msg.setLen(len);
            // 让下游处理器读取到msg对象
            out.add(msg);
        }
    }
}